package model

import (
	"errors"
	"gopkg.in/mgo.v2/bson"
	"src/util/time"
)

type Notice struct {
	ID        bson.ObjectId `bson:"_id,omitempty" json:"id,omitempty"`
	Content   []string      `json:"content" bson:"content"`
	IssueTime int64         `bson:"issue_time" json:"issue_time"`
}

func CreatNotice(content []string) (Notice, error) {
	NewNotice := Notice{
		Content:   content,
		IssueTime: time.GetSecondTimestamp(),
	}
	err := insertNotice(NewNotice)
	if err != nil {
		return Notice{}, err
	}
	query := bson.M{
		"issue_time": NewNotice.IssueTime,
	}
	return findNotice(query, DefaultSelector)
}

func ChangeNotice(id string, newcontent []string) error {
	if !bson.IsObjectIdHex(id) {
		return errors.New("id param error")
	}
	findquery := bson.M{
		"_id": bson.ObjectIdHex(id),
	}
	updataquery := bson.M{
		"$set": bson.M{
			"content": newcontent,
		},
	}
	return updateNotice(findquery, updataquery)
}

func GetNoticeAll() ([]Notice, error) {
	query := bson.M{}
	return findNoticesALL(query)
}

func GetNewNotice() (Notice, error) {
	query := bson.M{}
	fields := []string{
		"-issue_time",
	}
	newnotice, err := findNotices(query, DefaultSelector, 1, 1, fields...)
	if len(newnotice) == 0 {
		return Notice{}, err
	}
	return newnotice[0], err
}

func DeleteNotice(id string) error {
	if !bson.IsObjectIdHex(id) {
		return errors.New("id param error")
	}
	return deleteNotice(bson.ObjectIdHex(id))
}

/*************/
func updateNotice(query, update interface{}) error {
	sess := globalSess.Clone()
	defer sess.Close()
	Table := sess.DB(DBNAME).C(NoticeTABLE)

	return Table.Update(query, update)
}
func insertNotice(docs ...interface{}) error {
	sess := globalSess.Clone()
	defer sess.Close()
	Table := sess.DB(DBNAME).C(NoticeTABLE)

	return Table.Insert(docs...)
}
func findNotice(query, selector interface{}) (Notice, error) {
	sess := globalSess.Copy()
	defer sess.Close()
	Table := sess.DB(DBNAME).C(NoticeTABLE)

	Notice := Notice{}
	err := Table.Find(query).Select(selector).One(&Notice)
	return Notice, err
}
func findNoticeNum(query interface{}) (int, error) {
	sess := globalSess.Copy()
	defer sess.Close()
	Table := sess.DB(DBNAME).C(NoticeTABLE)

	return Table.Find(query).Count()
}
func findNotices(query, selector interface{}, page, perPage int, fields ...string) ([]Notice, error) {
	sess := globalSess.Copy()
	defer sess.Close()
	Table := sess.DB(DBNAME).C(NoticeTABLE)

	Notices := []Notice{}
	err := Table.Find(query).Select(selector).Sort(fields...).Skip((page - 1) * perPage).Limit(perPage).All(&Notices)
	return Notices, err
}
func findNoticesALL(query interface{}) ([]Notice, error) {
	sess := globalSess.Copy()
	defer sess.Close()
	Table := sess.DB(DBNAME).C(NoticeTABLE)

	Notices := []Notice{}
	err := Table.Find(query).All(&Notices)
	return Notices, err
}
func deleteNotice(id bson.ObjectId) error {
	sess := globalSess.Clone()
	defer sess.Close()
	Table := sess.DB(DBNAME).C(NoticeTABLE)
	return Table.RemoveId(id)
}
